using System.IO;
using Bookvar.ObjectModel;

namespace Bookvar.ServiceModel.Actions
{
    public abstract class ResourcePersistenceAction : PersistenceAction
    {
        private readonly IFileResource resource;
        private const int BufferSize = 1024;

        protected IFileResource Resource
        {
            get { return resource; }
        }

        protected ResourcePersistenceAction( IPersistenceService persistenceService, MindMap mindmap,
                                             IFileResource resource )
            : base( persistenceService, mindmap )
        {
            Contract.RequiresNotNull( resource, "resource" );

            this.resource = resource;
        }

        protected void CopyResourceStream( Stream target )
        {
            using ( var resourceStream = PersistenceService.LoadFileResourceFromPersistence( Mindmap.Key, Resource ) )
            {
                resourceStream.Seek( 0, SeekOrigin.Begin );
                byte[] buffer = new byte[BufferSize];
                int bytesRead;
                while ( ( bytesRead = resourceStream.Read( buffer, 0, BufferSize ) ) > 0 )
                {
                    target.Write( buffer, 0, bytesRead );
                }
            }
        }
    }
}